<?php

// @formatter:off
/**
 * @file WCServicesFactory.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-05-04 01:33:52 +0000 (Sun, 04 May 2014) $
 *
 * $Id: WCServicesFactory.php 111 2014-05-04 01:33:52Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/includes/services/WCServicesFactory.php $
 */
// @formatter:on


class WCServicesFactory extends WCFactory {
	//
	// Public static methods.
	public static function CreateService($path) {
		$out = false;

		$ok = true;
		$errno = 200;
		$error = "";
		$file = __FILE__;
		$line = __LINE__;

		if($path) {
			//
			// Loading global pointers.
			global $wcServices;

			$path = explode(":", str_replace("/", ":", $path));
			$serviceGroup = array_shift($path);
			$serviceManager = implode(":", $path);

			if(isset($wcServices[$serviceGroup][$serviceManager])) {
				if(!is_array($wcServices[$serviceGroup][$serviceManager])) {
					$wcServices[$serviceGroup][$serviceManager] = array(
						"class" => WC_SERVICE_CLASS_NAME,
						"path" => $wcServices[$serviceGroup][$serviceManager]
					);
				}
				//
				// Checking service file to include (if any).
				if(isset($wcServices[$serviceGroup][$serviceManager]["path"])) {
					if(!is_readable($wcServices[$serviceGroup][$serviceManager]["path"])) {
						$line = __LINE__;
						$errno = WC_HTTPERROR_INTERNAL_SERVER_ERROR;
						$error = "File '{$wcServices[$serviceGroup][$serviceManager]["path"]}' is not readable";
						$ok = false;
					} else {
						require_once $wcServices[$serviceGroup][$serviceManager]["path"];
					}
				}
				//
				// Checking if there's a manager class configured.
				if($ok && !isset($wcServices[$serviceGroup][$serviceManager]["class"])) {
					$wcServices[$serviceGroup][$serviceManager]["class"] = WC_SERVICE_CLASS_NAME;
				}
				//
				// Checking if there's a manager class configured.
				if($ok && !class_exists($wcServices[$serviceGroup][$serviceManager]["class"])) {
					$line = __LINE__;
					$errno = WC_HTTPERROR_INTERNAL_SERVER_ERROR;
					$error = "Class '{$wcServices[$serviceGroup][$serviceManager]["class"]}' doesn't exist";
					$ok = false;
				}
				//
				// Creating and running service.
				if($ok) {
					$out = new $wcServices[$serviceGroup][$serviceManager]["class"]();
				}
			} else {
				$line = __LINE__;
				$errno = WC_HTTPERROR_BAD_REQUEST;
				$error = "Service '{$serviceGroup}:{$serviceManager}' not recognized";
				$ok = false;
			}
		} else {
			$line = __LINE__;
			$errno = WC_HTTPERROR_BAD_REQUEST;
			$error = "Wrong parameters for service";
			$ok = false;
		}

		if(!$ok) {
			$out = new WCServiceDummy();
			$out->setError($errno, $error, array(
				"file" => $file,
				"line" => $line
			));
		}

		return $out;
	}
}
